// pages/signIn/signIn.js
var common = require("../../../common/common.js").common;

var app = getApp();

const {$Toast: $Toast} = require("../../../dist/base/index");

Page({
    /**
   * 页面的初始数据
   */
    data: {
        bgHidden: true,
        signSuccessModule: true,
        signRulesModule: true,
        signButt: "立即签到",
        signTip: "今天最高可得积分",
        signStatus: 1,
        loading: false,
        tommorowSignNum: "",
        maxNum: 0,
        signButtDisabled: false
    },
    //获取用户信息
    getUsersInfomation: function() {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        common.request({
            endpoint: "My/myinfo/myinfo",
            method: "post",
            data: {
                openid: openid
            },
            success: res => {
                console.log(res);
                that.setData({
                    info: res.extra
                });
            }
        });
    },
    //获取数据
    getData() {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        var nows = new Date();
        that.setData({
            loading: true
        });
        common.request({
            endpoint: "Integral/sign/sign_show",
            method: "post",
            data: {
                openid: openid,
                year: nows.getFullYear(),
                month: nows.getMonth() + 1
            },
            success: res => {
                console.log(res, "integration");
                var now = new Date();
                var date = now.getDate();
                var data = res.extra;
                var now = new Date();
                if (data.rule) {
                    var gift_day_t = data.gift_day.split("-");
                    //礼品日转化成秒
                                        data.gift_day_time = new Date(gift_day_t[0], gift_day_t[1], gift_day_t[2], 0, 0, 0).getTime();
                    //console.log(res.extra)
                                        var nowDate = now.getDate() < 10 ? "0" + now.getDate() : now.getDate();
                    //遍历日历
                                        data.detail.day.forEach((item, index) => {
                        item.times = new Date(now.getFullYear(), now.getMonth() + 1, item.date, 0, 0, 0).getTime();
                        if (item.date < 10) {
                            //小于10的日期，前面加0
                            item.date = "0" + item.date;
                        }
                        if (item.date == nowDate && item.sta == 1) {
                            //今天已签到，改变签到按钮，并且不允许再次签到
                            that.setData({
                                signStatus: 0,
                                signButt: "签到成功",
                                signTip: "今天已获得奖励"
                            });
                        }
                        //计算明日签到
                                                var tommorowTimes = new Date(now.getFullYear(), now.getMonth() + 1, now.getDate() + 1, 0, 0, 0).getTime();
                        var rules = data.rule.split(",");
                        if (tommorowTimes != data.gift_day_time) {
                            //明天不是礼品日，随机积分
                            that.setData({
                                tommorowSignNum: rules[0] + "~" + rules[1],
                                maxNum: rules[1]
                            });
                        } else {
                            //礼品日，签到积分随机数加额外积分
                            that.setData({
                                tommorowSignNum: Number(rules[0]) + Number(data.rule_integ) + "~" + (Number(rules[1]) + Number(data.rule_integ)),
                                maxNum: Number(rules[1]) + Number(data.rule_integ)
                            });
                        }
                    });
                    that.setData({
                        showData: data,
                        scrollNowDate: "scroll" + that.data.nowDate,
                        loading: false
                    });
                } else {
                    wx.showModal({
                        title: "提示",
                        content: "后台未设置签到规则，请联系平台设置",
                        showCancel: false,
                        success(res) {
                            if (res.confirm) wx.navigateBack({});
                        }
                    });
                }
            }
        });
    },
    //积分规则按钮
    rulestap() {
        this.setData({
            bgHidden: false,
            signRulesModule: false
        });
    },
    //立即签到
    signInTap() {
        var that = this;
        that.setData({
            signButtDisabled: true
        });
        var now = new Date();
        var nowDate = now.getDate() < 10 ? "0" + now.getDate() : now.getDate();
        //没有签到的可以签到，已经签到的提示今天已签到
                if (that.data.signStatus == 1) {
            var openid = wx.getStorageSync("user").openid;
            common.request({
                endpoint: "Integral/sign/sign",
                //
                method: "post",
                data: {
                    openid: openid,
                    year: now.getFullYear(),
                    month: now.getMonth + 1,
                    day: now.getDate()
                },
                success: res => {
                    console.log(res, "data");
                    var showData = that.data.showData;
                    //签到成功，总积分增加
                                        showData.m_integ = Number(showData.m_integ) + Number(res.extra.integral) + Number(res.extra.extra_integral);
                    //签到成功，连续签到天数增加
                                        showData.l_day = Number(showData.l_day) + 1;
                    showData.detail.day.forEach((item, index) => {
                        if (item.date == nowDate) {
                            //改变签到日状态
                            item.sta = 1;
                        }
                    });
                    that.setData({
                        bgHidden: false,
                        signSuccessModule: false,
                        signStatus: 0,
                        signButt: "签到成功",
                        signTip: "今天已获得奖励",
                        integral: res.extra.integral,
                        extra_integral: Number(res.extra.extra_integral),
                        todayIntegral: Number(res.extra.integral),
                        showData: showData,
                        signButtDisabled: false
                    });
                },
                fail(e) {
                    //请求失败，打开签到按钮
                    that.setData({
                        signButtDisabled: false
                    });
                }
            });
        } else {
            //提示已签到
            $Toast({
                content: "您今天已经签到了哟~~"
            });
            that.setData({
                signButtDisabled: false
            });
        }
    },
    //取消
    cancel() {
        this.setData({
            bgHidden: true,
            signSuccessModule: true,
            signRulesModule: true
        });
    },
    // 点击礼品提示
    giftToast() {
        var that = this;
        $Toast({
            content: "连续签到" + that.data.showData.rule_ldays + "天即可多得" + that.data.showData.rule_integ + "积分"
        });
    },
    getWeekStartDateAndEndDateRange() {
        var that = this;
        console.log("q2");
        let oneDayLong = 24 * 60 * 60 * 1e3;
        let now = new Date();
        let mondayTime = now.getTime() - (now.getDay() - 1) * oneDayLong;
        let sundayTime = now.getTime() + (7 - now.getDay()) * oneDayLong;
        let monday = new Date(mondayTime);
        let sunday = new Date(sundayTime);
        let weekRange = [ monday, sunday ];
        let startYear = monday.getFullYear();
        let startMonth = monday.getMonth() + 1;
        let startDate = monday.getDate();
        let endYear = sunday.getFullYear();
        let endMonth = sunday.getMonth() + 1;
        let endDate = sunday.getDate();
        if (startYear != endYear) {
            //跨年 开始时间到年底，次年年初到结束日期
            var canlendar = this.getWeekDateArry("year", now, startDate, endDate);
            that.setData({
                canlendar: canlendar
            });
        } else {
            //不跨年
            if (startMonth != endMonth) {
                //跨月
                var canlendar = this.getWeekDateArry("month", now, startDate, endDate);
                that.setData({
                    canlendar: canlendar
                });
            } else {
                var canlendar = this.getWeekDateArry("week", now, startDate, endDate);
                that.setData({
                    canlendar: canlendar
                });
            }
        }
        // console.log(endYear + "---" + endMonth + "---" + endDate);
        // return weekRange;
        },
    //获取周日期列表
    getWeekDateArry(status, now, startDate, endDate) {
        var that = this;
        var dateArry = [];
        switch (status) {
          case "year":
            var lastday = that.getLastDay(now, startDate);
            var date = startDate - 1;
            //console.log(lastday);
                        for (var i = 0; i < lastday[1] - lastday[0] + 1; i++) {
                date++;
                var item = {
                    date: now.getFullYear() + "-12-" + date,
                    getDate: date
                };
                dateArry.push(item);
            }
            for (var i = 1; i < endDate + 1; i++) {
                var item = {
                    date: now.getFullYear() + 1 + "-01-" + "0" + i,
                    getDate: "0" + i
                };
                dateArry.push(item);
            }
            break;

          case "month":
            var lastday = that.getLastDay(now, startDate);
            var date = startDate - 1;
            //console.log(lastday);
                        for (var i = 0; i < lastday[1] - lastday[0] + 1; i++) {
                date++;
                var item = {
                    date: now.getFullYear() + "-" + (now.getMonth() + 1 < 10 ? "0" + (now.getMonth() + 1) : now.getMonth() + 1) + "-" + date,
                    getDate: date
                };
                dateArry.push(item);
            }
            for (var i = 1; i < endDate + 1; i++) {
                var item = {
                    date: now.getFullYear() + "-" + (now.getMonth() + 2 < 10 ? "0" + (now.getMonth() + 2) : now.getMonth() + 2) + "-0" + i,
                    getDate: "0" + i
                };
                dateArry.push(item);
            }
            break;

          case "week":
            var date = startDate - 1;
            //console.log(lastday);
                        for (var i = 0; i < endDate - startDate + 1; i++) {
                date++;
                var item = {
                    date: now.getFullYear() + "-" + (now.getMonth() < 9 ? "0" + (now.getMonth() + 1) : now.getMonth() + 1) + "-" + (date < 10 ? "0" + date : date),
                    getDate: date
                };
                dateArry.push(item);
            }
            break;
        }
        console.log(dateArry, "eqwe");
        return dateArry;
    },
    //获取本月最后一天
    getLastDay(date, startDate) {
        //需要现在时间，本周开始日期
        //var date = new Date();
        var currentMonth = date.getMonth();
        var nextMonth = ++currentMonth;
        var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
        var oneDay = 1e3 * 60 * 60 * 24;
        var lastDate = new Date(nextMonthFirstDay - oneDay);
        var dateArry = [ startDate, lastDate.getDate() ];
        return dateArry;
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        wx.hideShareMenu();
        this.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        console.log(this.data.domain);
        //this.getWeekStartDateAndEndDateRange();
                var now = new Date();
        this.setData({
            now: now.getFullYear() + "-" + (now.getMonth() < 9 ? "0" + (now.getMonth() + 1) : now.getMonth() + 1) + "-" + (now.getDate() < 10 ? "0" + now.getDate() : now.getDate()),
            now2: now.getFullYear() + "." + (now.getMonth() < 9 ? "0" + (now.getMonth() + 1) : now.getMonth() + 1) + "." + (now.getDate() < 10 ? "0" + now.getDate() : now.getDate()),
            nowDate: now.getDate() < 10 ? "0" + now.getDate() : now.getDate()
        });
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        this.getUsersInfomation();
        this.getData();
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {}
});